from sklearn.datasets import load_boston

# 导入波斯顿的房价数据
boston = load_boston()


from sklearn.cross_validation import train_test_split
import numpy as np

# 提取出训练、测试集及目标值
X = boston.data
y = boston.target
# print(X)

# 随机采样25%的数据构建测试样本，其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=33, test_size=0.25)

# 分析回归目标值的差异
# print('目标值最大值：',np.max(y))
# print('目标值最小值:',np.min(y))
# print('目标平均值:',np.mean(y))


#  从sklearn.preprocessing导入数据标准化模块
from sklearn.preprocessing import StandardScaler

# 分别初始化对特征和目标值的标准化模块
ss_X = StandardScaler()
ss_y= StandardScaler()

# 分别对训练和测试数据的特征以及目标值进行标准化处理
X_train = ss_X.fit_transform(X_train)
X_test = ss_X.fit_transform(X_test)
# y_train = ss_y.fit_transform(y_train)
# y_test = ss_y.transform(y_test)
y_train = ss_y.fit_transform(y_train.reshape(-1, 1))
y_test = ss_y.transform(y_test.reshape(-1, 1))


# 从sklearn.tree中导入DecisionTreeRegressior
from sklearn.tree import DecisionTreeRegressor
# 使用默认配置初始化DecisionTreeRegressor
dtr = DecisionTreeRegressor()
# 用波士顿房价的训练数据构建回归树
dtr.fit(X_train, y_train.ravel())
# 使用默认配置的单一回归树对测试数据进行预测，并将预测值存储在变量dtr_y_predict中
dtr_y_predict = dtr.predict(X_test)
# print(dtr_y_predict)

# 使用R-squared、MSE、MAE三种指标对默认配置的回归树在测试集上进行性能评估
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
print('R-squared value of DecisionTreeRegressor:', dtr.score(X_test, y_test))
print('The mean squared error of DecisionTreeRegressor:', mean_squared_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(dtr_y_predict)))
print('The mean abolute error of DecisionTreeRegressor:', mean_absolute_error(ss_y.inverse_transform(y_test), ss_y.inverse_transform(dtr_y_predict)))
